package com.sap.health.tracker.threads;

import org.json.JSONArray;
import org.json.JSONObject;

import com.sap.health.tracker.R;
import com.sap.health.tracker.json.JSONFunctions;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class NotificationsThread extends Activity {
	
	// JSON Response node name
    private static String KEY_SUCCESS = "success";
    //Layout assets.
    private TextView mGetErrorMsg;
	private TableLayout mNotificationsTable;
	private Context mCtx;
	private String mUserID;
	private String mSessionToken;
	private ProgressDialog mLoadingDialog;	
	/**
	 * Runs when Class is first created.
	 * @param ctx
	 */
    public NotificationsThread(Context ctx, String userId, String sessionToken, 
    		final TextView getErrorMsg,
    		final TableLayout hospitalTable,
    		final ImageView refresh) {
    	
    	this.mGetErrorMsg = getErrorMsg;
		this.mNotificationsTable = hospitalTable;	
    	this.mCtx = ctx;
    	this.mUserID = userId;
    	this.mSessionToken = sessionToken;
    	// set refresh button listener.
    	refresh.setOnClickListener(new OnClickListener() {
         	public void onClick(View v) {
         		refresh();
         	}
         });   	
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // needed but not used.
    }
    /**
     * Get the users notifications.
     */
    public void getNotifications(){
    	   	
    	new Thread(new Runnable() {
    		@Override
            public void run() {
            	// let the user know it's busy.
    			createProgressDialog();
    			// connect to server and get notifications.
                JSONFunctions userFunction = new JSONFunctions();
                JSONObject json = userFunction.getNotifications(mUserID, mSessionToken);
                // check for login response
                try {
                	if (json.getString(KEY_SUCCESS) != null) {
                		//hide error message from user.
                		emptyErrorMessage();              		
                		String res = json.getString(KEY_SUCCESS);
                		if(Integer.parseInt(res) == 1){
                			// get JSON arrays.
                			JSONArray jsonNotificationType = json.getJSONArray("notification_type");             			             			
                			JSONArray jsonNotifications = json.getJSONArray("notification_message");             			             			
                			// pass individual notification.
                			for(int i = 0; i < jsonNotifications.length(); i++){
                                // get each notification                							
                				notificationsUiHandler(jsonNotifications.getString(i), jsonNotificationType.getString(i)); 
                			}             					                                                        
                		} else if(Integer.parseInt(res) == 3){
                			//let the user know there was no notifications.
       		        	 	errorMessage("There are currently no notifications.");
                		}else {
                			//let the user know there was an error.
       		        	 	errorMessage("Error Accessing Database");
                		}
                     }
                 } catch (Exception e) {
                	 //TODO better exception handling.
                     e.printStackTrace();
                     // let the user know there was an error.
		        	 errorMessage("Network Connection Error");		        	 
                 }
                 dismissProgressDialog();
    		}                  	
    	}).start();		
    }
    /**
     * Handle each notifiction and pass it to the UI.
     * @param notification
     * @param type
     */
    private void notificationsUiHandler(
    		final String notification, 
    		final String type){   	
    	runOnUiThread(new Runnable() {
            public void run() {
            	// Declare a new row
	           	TableRow nameRow = new TableRow(mCtx);
	           	// create text view.
	           	TextView nameTx = new TextView(mCtx);
	            nameTx.setTextSize(16f);
	            nameTx.setText(notification);
	            nameTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	            	 
	           	// add views to the row
	           	nameRow.addView(nameTx); // you would actually want to set properties on this before adding it
	           	nameRow.setPadding(10, 10, 0, 10);
	           	// help dialog.
	           	nameRow.setOnLongClickListener(new OnLongClickListener() { 
	                @Override
	                public boolean onLongClick(View v) {
	                    helpDialog("These are your notifications.");               	                	
	                    return true;
	                }
	           	});         	 
	           	// add the row to the table layout
	           	mNotificationsTable.addView(nameRow);          	 
	           	//Used for creating a horizontal line to separate .          	          	           	 
	           	View ruler = new View(mCtx); ruler.setBackgroundColor(0xFFDEDEDE);
	           	mNotificationsTable.addView(ruler, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2));       	 
            }
        });
    }
    /**
     * Displays the help dilaog.
     * @param message
     */
    private void helpDialog(final String message){
    	
		// new dialog
		final Dialog dialog = new Dialog(mCtx);
		dialog.setContentView(R.layout.popup);
		dialog.setTitle("Help options");		
		TableRow noteRow = new TableRow(mCtx);
      	// create text view.
      	TextView noteTx = new TextView(mCtx);
      	noteTx.setText(message);
      	noteTx.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));           	 
      	// add views to the row
      	noteRow.addView(noteTx);   	 
      	noteRow.setPadding(10, 10, 0, 10);       
      	TableLayout dialogTable = (TableLayout) dialog.findViewById(R.id.dialogTable);    
      	// add the row to the table layout
      	dialogTable.addView(noteRow);		 	
		Button dialogButton = (Button) dialog.findViewById(R.id.dismiss);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
 
		dialog.show();	
	}
    /**
     * Refresh the layout.
     */
    private void refresh(){
    	mNotificationsTable.removeAllViews();
    	getNotifications();
    	
    }
    /**
     * Empty the error message.
     */
    private void emptyErrorMessage(){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetErrorMsg.setText("");
             	mGetErrorMsg.setVisibility(View.INVISIBLE);
            }
		});
    }
    /**
     * Create error message.
     * @param error
     */
    private void errorMessage(final String error){
    	runOnUiThread(new Runnable() {
			public void run() {
				mGetErrorMsg.setText(error);
             	mGetErrorMsg.setVisibility(View.VISIBLE);
            }
		});
    }
    /**
     * Dismiss progress dialog.
     */
    private void dismissProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// hide progress spinner now that thread is finished.
            	//loadingSpinner.setVisibility(View.INVISIBLE);
            	mLoadingDialog.dismiss();
            }
        });
    }
    /**
     * Create progress dialog.
     */
    private void createProgressDialog(){
    	runOnUiThread(new Runnable() {
            public void run() {
            	// show progress spinner to let the user know it's working.
            	//loadingSpinner.setVisibility(View.VISIBLE);
            	mLoadingDialog = new ProgressDialog(mCtx);
                mLoadingDialog.setTitle("");
                mLoadingDialog.setMessage("Loading. Please wait...");
                mLoadingDialog.show();
            }
        });
    }
}
